package com.github.byakkili.bim.core.support.collection;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.util.StrUtil;
import com.github.byakkili.bim.core.BimSession;
import lombok.Getter;

import java.util.Set;

/**
 * @author Guannian Li
 */
@Getter
public class Topics {
    /**
     * key, set
     */
    private ReadWriteLockMap<String, Set<BimSession>> strSetMap = new ReadWriteLockMap<>();

    /**
     * 绑定
     *
     * @param session 会话
     */
    public void bind(BimSession session) {
        CollUtil.emptyIfNull(session.getTopics()).forEach(topic -> {
            if (StrUtil.isNotBlank(topic)) {
                Set<BimSession> sessions = strSetMap.get(topic);
                if (sessions == null) {
                    sessions = new ConcurrentHashSet<>();
                    Set<BimSession> previousValue = strSetMap.putIfAbsent(topic, sessions);
                    if (previousValue != null) {
                        sessions = previousValue;
                    }
                }
                sessions.add(session);
            }
        });
    }

    /**
     * 解绑
     *
     * @param session 会话
     */
    public void unbind(BimSession session) {
        CollUtil.emptyIfNull(session.getTopics()).forEach(topic -> {
            if (StrUtil.isNotBlank(topic)) {
                strSetMap.getWriteLock().lock();
                try {
                    Set<BimSession> sessions = strSetMap.get(topic);
                    if (sessions != null && sessions.remove(session) && sessions.isEmpty()) {
                        strSetMap.remove(topic);
                    }
                } finally {
                    strSetMap.getWriteLock().unlock();
                }
            }
        });
    }

    /**
     * 获取会话列表
     */
    public Set<BimSession> getSessions(String topic) {
        return strSetMap.get(topic);
    }
}
